<?php
namespace Payment\Controller;
use Think\Controller;
/*
      首页
*/
class AlipayController extends InitController {

    /**
     * 支付页面
     */
    public function AliPayIndex(){
		
      $alipayurl = "http://wappaygw.alipay.com/service/rest.htm";
     
      $payoption = I('payoption');
      
      $payoption = base64_decode($payoption);
      if(empty($payoption)){
          exit;
      }

      $payval=explode('&',$payoption);
      $payment=array();
      foreach($payval as $pk=>$v){
          if(!empty($v)){
              $paymentarray=explode('=',$v);
              $payment[$paymentarray[0]]=$paymentarray[1];
          }
      }
      $out_trade_no = $payment['out_trade_no'];
      $body = $payment['body'];

      //$memberpayment = C('PAYMENT_SETTING');//配置文件，用于测试
	  $memberpayment = M('Options')->where(array('option_name'=>'alipay'))->getField('option_value');
	  if(empty($memberpayment)){
			exit('商家没有开通支付方式');
	  }
	  $paymentinfo = unserialize($memberpayment);
      
      //获取订单id 以及对应的模块
      $payinfo = M('user_paysn')->alias('ps')->join("left join __PAY_LOG__ as pl on ps.id = pl.pay_sn_id")
      ->where("pay_sn = '{$out_trade_no}'")
      ->field("pl.order_id , pl.module ")->find();
	
      $Rmodule = ucfirst(strtolower($payinfo['module']));
      //通过内部方法，调用对应模块的订单金额
		
      $r = R($Rmodule."/Payment/SendPaymentMoneyCount",array($payinfo['order_id']));
	  
      $location = $r['host']; //支付完成回跳地址
      $total_fee = $r['count']; //支付宝元单位

      $set = array();
      $set['service'] = 'alipay.wap.trade.create.direct';
      $set['format'] = 'xml';
      $set['v'] = '2.0';
      $set['partner'] = $paymentinfo['partner'];
      $set['req_id'] = $out_trade_no;
      $set['sec_id'] = 'MD5';

      $host = "http://".$_SERVER['HTTP_HOST']."/";
      $callback = $location;
      $notify = $host . 'Index.php/Payment/Alipay/order_notify';
      $merchant = $host ;
      $expire = 10;
      $set['req_data'] = "<direct_trade_create_req>
                  <subject>{$body}</subject>
                  <out_trade_no>{$out_trade_no}</out_trade_no>
                  <total_fee>{$total_fee}</total_fee>
                  <seller_account_name>{$paymentinfo['account']}</seller_account_name>
                  <call_back_url>{$callback}</call_back_url>
                  <notify_url>{$notify}</notify_url>
                  
                  <merchant_url>{$merchant}</merchant_url>
                  <pay_expire>{$expire}</pay_expire>
                </direct_trade_create_req>";//<out_user>1</out_user>
      $prepares = array();

      foreach($set as $key => $value) {
        if($key != 'sign') {
          $prepares[] = "{$key}={$value}";
        }
      }

      sort($prepares);
      $string = implode($prepares, '&');
      $string .= $paymentinfo['secret'];
      $set['sign'] = md5($string);

      $curl = new  \Org\Util\Curl;
      $response = $curl->ihttp_request($alipayurl . '?' . http_build_query($set),null,true);

      $ret = array();
      @parse_str($response['content'], $ret);
      foreach($ret as &$v) {
        $v = str_replace('\"', '"', $v);
      }

      if(!is_array($ret)) {
        exit("支付失败");
      }
      //判断错误
      if($ret['res_error']) {
          $error = simplexml_load_string($ret['res_error'], 'SimpleXMLElement', LIBXML_NOCDATA);
          if($error instanceof SimpleXMLElement && $error->detail) {
            p(strval($error->detail));
          }
      }

      //比较参数是否正确
      if($ret['partner'] == $set['partner'] && $ret['req_id'] == $set['req_id'] && $ret['sec_id'] == $set['sec_id'] && $ret['service'] == $set['service'] && $ret['v'] == $set['v']) {
        $prepares = array();

        foreach($ret as $key => $value) {
          if($key != 'sign') {
            $prepares[] = "{$key}={$value}";
          }
        }

        sort($prepares);
        $string = implode($prepares, '&');
        $string .= $paymentinfo['secret'];
      
        if(md5($string) == $ret['sign']) {
          $obj = simplexml_load_string($ret['res_data'], 'SimpleXMLElement', LIBXML_NOCDATA);
          if($obj->request_token) {
            $token = strval($obj->request_token);
            $set = array();
            $set['service'] = 'alipay.wap.auth.authAndExecute';
            $set['format'] = 'xml';
            $set['v'] = '2.0';
            $set['partner'] = $paymentinfo['partner'];
            $set['sec_id'] = 'MD5';
            $set['req_data'] = "<auth_and_execute_req><request_token>{$token}</request_token></auth_and_execute_req>";
            
            //返回参数用于页面显示
            $set['fee']     = $total_fee;
            $set['ordersn'] = $out_trade_no;
            
            $prepares = array();
            foreach($set as $key => $value) {
              if($key != 'sign') {
                $prepares[] = "{$key}={$value}";
              }
            }
            sort($prepares);
            $string = implode($prepares, '&');
            $string .= $paymentinfo['secret'];
            $set['sign'] = md5($string);
            $url = $alipayurl . '?' . http_build_query($set);
            $this->assign("url",$url);
            $this->display('AliPayIndex');
          }

        }

      }

    }

}